"""
AI算法相关的数据模型定义
"""
from datetime import datetime
from typing import List, Dict, Any, Optional, Union
from pydantic import BaseModel, Field, field_validator
from enum import Enum


class BehaviorType(str, Enum):
    """行为类型枚举"""
    NORMAL = "normal"
    SUSPICIOUS = "suspicious"
    AGGRESSIVE = "aggressive"
    CROWDING = "crowding"
    LOITERING = "loitering"
    RUNNING = "running"
    FIGHTING = "fighting"
    FALLING = "falling"
    UNKNOWN = "unknown"


class AlertLevel(str, Enum):
    """告警级别枚举"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"


class DetectionStatus(str, Enum):
    """检测状态枚举"""
    PENDING = "pending"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"


class BoundingBox(BaseModel):
    """边界框模型"""
    x1: float = Field(..., description="左上角X坐标")
    y1: float = Field(..., description="左上角Y坐标")
    x2: float = Field(..., description="右下角X坐标")
    y2: float = Field(..., description="右下角Y坐标")
    confidence: float = Field(..., ge=0, le=1, description="置信度")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "x1": 100.0,
                "y1": 150.0,
                "x2": 200.0,
                "y2": 400.0,
                "confidence": 0.95
            }
        }
    }


class DetectionResult(BaseModel):
    """检测结果模型"""
    detection_id: str = Field(..., description="检测ID")
    object_type: str = Field(..., description="对象类型")
    bbox: BoundingBox = Field(..., description="边界框")
    confidence: float = Field(..., ge=0, le=1, description="置信度")
    timestamp: datetime = Field(..., description="检测时间")
    camera_id: str = Field(..., description="摄像头ID")
    frame_id: Optional[str] = Field(None, description="帧ID")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "detection_id": "det_123456",
                "object_type": "person",
                "bbox": {
                    "x1": 100.0,
                    "y1": 150.0,
                    "x2": 200.0,
                    "y2": 400.0,
                    "confidence": 0.95
                },
                "confidence": 0.95,
                "timestamp": "2024-01-01T12:00:00Z",
                "camera_id": "cam_001",
                "frame_id": "frame_789"
            }
        }
    }


class TrackingResult(BaseModel):
    """跟踪结果模型"""
    track_id: str = Field(..., description="跟踪ID")
    object_type: str = Field(..., description="对象类型")
    trajectory: List[BoundingBox] = Field(..., description="轨迹点列表")
    start_time: datetime = Field(..., description="开始时间")
    end_time: Optional[datetime] = Field(None, description="结束时间")
    camera_id: str = Field(..., description="摄像头ID")
    is_active: bool = Field(True, description="是否活跃")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "track_id": "track_001",
                "object_type": "person",
                "trajectory": [],
                "start_time": "2024-01-01T12:00:00Z",
                "camera_id": "cam_001",
                "is_active": True
            }
        }
    }


class BehaviorAnalysisResult(BaseModel):
    """行为分析结果模型"""
    analysis_id: str = Field(..., description="分析ID")
    camera_id: str = Field(..., description="摄像头ID")
    behavior_type: BehaviorType = Field(..., description="行为类型")
    confidence: float = Field(..., ge=0, le=1, description="置信度")
    timestamp: datetime = Field(..., description="分析时间")
    duration: Optional[float] = Field(None, description="持续时间(秒)")
    location: Optional[Dict[str, float]] = Field(None, description="位置信息")
    involved_objects: List[str] = Field([], description="涉及对象ID列表")
    description: str = Field("", description="行为描述")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "analysis_id": "analysis_123",
                "camera_id": "cam_001",
                "behavior_type": "suspicious",
                "confidence": 0.85,
                "timestamp": "2024-01-01T12:00:00Z",
                "duration": 5.2,
                "location": {"x": 320, "y": 240},
                "involved_objects": ["person_001", "person_002"],
                "description": "检测到可疑行为"
            }
        }
    }


class DetectionRequest(BaseModel):
    """检测请求模型"""
    camera_id: str = Field(..., description="摄像头ID")
    algorithm_type: str = Field(..., description="算法类型")
    config: Optional[Dict[str, Any]] = Field(None, description="算法配置")
    start_time: Optional[datetime] = Field(None, description="开始时间")
    end_time: Optional[datetime] = Field(None, description="结束时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "cam_001",
                "algorithm_type": "person_detection",
                "config": {
                    "confidence_threshold": 0.7,
                    "nms_threshold": 0.4
                },
                "start_time": "2024-01-01T12:00:00Z",
                "end_time": "2024-01-01T13:00:00Z"
            }
        }
    }


class DetectionResponse(BaseModel):
    """检测响应模型"""
    task_id: str = Field(..., description="任务ID")
    status: DetectionStatus = Field(..., description="检测状态")
    results: List[DetectionResult] = Field([], description="检测结果")
    total_count: int = Field(0, description="检测总数")
    processing_time: Optional[float] = Field(None, description="处理时间(秒)")
    created_at: datetime = Field(..., description="创建时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "task_id": "task_123",
                "status": "completed",
                "results": [],
                "total_count": 5,
                "processing_time": 2.5,
                "created_at": "2024-01-01T12:00:00Z"
            }
        }
    }


class BatchDetectionRequest(BaseModel):
    """批量检测请求模型"""
    camera_ids: List[str] = Field(..., min_length=1, description="摄像头ID列表")
    algorithm_type: str = Field(..., description="算法类型")
    config: Optional[Dict[str, Any]] = Field(None, description="算法配置")
    start_time: Optional[datetime] = Field(None, description="开始时间")
    end_time: Optional[datetime] = Field(None, description="结束时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_ids": ["cam_001", "cam_002", "cam_003"],
                "algorithm_type": "person_detection",
                "config": {
                    "confidence_threshold": 0.7
                }
            }
        }
    }


class BatchDetectionResponse(BaseModel):
    """批量检测响应模型"""
    batch_id: str = Field(..., description="批次ID")
    task_ids: List[str] = Field(..., description="任务ID列表")
    total_tasks: int = Field(..., description="总任务数")
    completed_tasks: int = Field(0, description="已完成任务数")
    failed_tasks: int = Field(0, description="失败任务数")
    created_at: datetime = Field(..., description="创建时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "batch_id": "batch_123",
                "task_ids": ["task_001", "task_002", "task_003"],
                "total_tasks": 3,
                "completed_tasks": 2,
                "failed_tasks": 0,
                "created_at": "2024-01-01T12:00:00Z"
            }
        }
    }


class AIModelConfig(BaseModel):
    """AI模型配置模型"""
    model_name: str = Field(..., description="模型名称")
    model_type: str = Field(..., description="模型类型")
    version: str = Field(..., description="模型版本")
    config: Dict[str, Any] = Field(..., description="模型配置")
    enabled: bool = Field(True, description="是否启用")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "model_name": "YOLOv8",
                "model_type": "object_detection",
                "version": "8.0.0",
                "config": {
                    "confidence_threshold": 0.7,
                    "nms_threshold": 0.4,
                    "max_detections": 100
                },
                "enabled": True
            }
        }
    }


class AlertRule(BaseModel):
    """告警规则模型"""
    rule_id: str = Field(..., description="规则ID")
    rule_name: str = Field(..., description="规则名称")
    behavior_type: BehaviorType = Field(..., description="行为类型")
    alert_level: AlertLevel = Field(..., description="告警级别")
    conditions: Dict[str, Any] = Field(..., description="触发条件")
    actions: List[str] = Field(..., description="告警动作")
    enabled: bool = Field(True, description="是否启用")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "rule_id": "rule_001",
                "rule_name": "打架行为告警",
                "behavior_type": "fighting",
                "alert_level": "high",
                "conditions": {
                    "confidence_threshold": 0.8,
                    "duration_threshold": 3.0
                },
                "actions": ["send_notification", "record_video"],
                "enabled": True
            }
        }
    }


class AlertEvent(BaseModel):
    """告警事件模型"""
    event_id: str = Field(..., description="事件ID")
    rule_id: str = Field(..., description="规则ID")
    camera_id: str = Field(..., description="摄像头ID")
    behavior_type: BehaviorType = Field(..., description="行为类型")
    alert_level: AlertLevel = Field(..., description="告警级别")
    confidence: float = Field(..., ge=0, le=1, description="置信度")
    timestamp: datetime = Field(..., description="事件时间")
    location: Optional[Dict[str, float]] = Field(None, description="位置信息")
    description: str = Field("", description="事件描述")
    resolved: bool = Field(False, description="是否已解决")
    resolved_at: Optional[datetime] = Field(None, description="解决时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "event_id": "event_123",
                "rule_id": "rule_001",
                "camera_id": "cam_001",
                "behavior_type": "fighting",
                "alert_level": "high",
                "confidence": 0.92,
                "timestamp": "2024-01-01T12:00:00Z",
                "location": {"x": 320, "y": 240},
                "description": "检测到打架行为",
                "resolved": False
            }
        }
    }


class ModelPerformanceMetrics(BaseModel):
    """模型性能指标模型"""
    model_name: str = Field(..., description="模型名称")
    total_inferences: int = Field(0, description="总推理次数")
    successful_inferences: int = Field(0, description="成功推理次数")
    failed_inferences: int = Field(0, description="失败推理次数")
    average_inference_time: float = Field(0.0, description="平均推理时间(毫秒)")
    average_confidence: float = Field(0.0, description="平均置信度")
    accuracy: Optional[float] = Field(None, description="准确率")
    precision: Optional[float] = Field(None, description="精确率")
    recall: Optional[float] = Field(None, description="召回率")
    f1_score: Optional[float] = Field(None, description="F1分数")
    last_updated: datetime = Field(..., description="最后更新时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "model_name": "YOLOv8",
                "total_inferences": 10000,
                "successful_inferences": 9950,
                "failed_inferences": 50,
                "average_inference_time": 25.5,
                "average_confidence": 0.87,
                "accuracy": 0.92,
                "precision": 0.89,
                "recall": 0.94,
                "f1_score": 0.91,
                "last_updated": "2024-01-01T12:00:00Z"
            }
        }
    }